package cn.iocoder.yudao.module.biz.controller.admin.documentImpl;

import cn.iocoder.yudao.module.biz.controller.admin.risk.basicManage.vo.BizBasicManageExcelVO;
import cn.iocoder.yudao.module.biz.controller.admin.risk.basicManage.vo.BizBasicManageImportRespVO;
import cn.iocoder.yudao.module.infra.dal.dataobject.oss.OssDO;
import cn.iocoder.yudao.module.infra.service.oss.OssService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.*;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.biz.controller.admin.documentImpl.vo.*;
import cn.iocoder.yudao.module.biz.dal.dataobject.documentImpl.BizDocumentImplDO;
import cn.iocoder.yudao.module.biz.convert.documentImpl.BizDocumentImplConvert;
import cn.iocoder.yudao.module.biz.service.documentImpl.BizDocumentImplService;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = "管理后台 - 文件落实")
@RestController
@RequestMapping("/biz/document-impl")
@Validated
public class BizDocumentImplController {

    @Resource
    private BizDocumentImplService documentImplService;
    @Resource
    private OssService ossService;

    @PostMapping("/create")
    @ApiOperation("创建文件落实")
    @PreAuthorize("@ss.hasPermission('biz:document-impl:create')")
    public CommonResult<String> createDocumentImpl(@Valid @RequestBody BizDocumentImplCreateReqVO createReqVO) {
        return success(documentImplService.createDocumentImpl(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新文件落实")
    @PreAuthorize("@ss.hasPermission('biz:document-impl:update')")
    public CommonResult<Boolean> updateDocumentImpl(@Valid @RequestBody BizDocumentImplUpdateReqVO updateReqVO) {
        documentImplService.updateDocumentImpl(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除文件落实")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('biz:document-impl:delete')")
    public CommonResult<Boolean> deleteDocumentImpl(@RequestParam("id") String id) {
        documentImplService.deleteDocumentImpl(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得文件落实")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('biz:document-impl:query')")
    public CommonResult<BizDocumentImplRespVO> getDocumentImpl(@RequestParam("id") String id) {
        BizDocumentImplDO documentImpl = documentImplService.getDocumentImpl(id);
        BizDocumentImplRespVO respVO = BizDocumentImplConvert.INSTANCE.convert(documentImpl);
        if(respVO.getFilePath() != null && !respVO.getFilePath().equals("")){
            Collection<String> fileIds=Arrays.asList(respVO.getFilePath().split(","));
            respVO.setOssDOList(ossService.selectByIds(fileIds));
        }
        return success(respVO);
    }

    @GetMapping("/list")
    @ApiOperation("获得文件落实列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    @PreAuthorize("@ss.hasPermission('biz:document-impl:query')")
    public CommonResult<List<BizDocumentImplRespVO>> getDocumentImplList(@RequestParam("ids") Collection<String> ids) {
        List<BizDocumentImplDO> list = documentImplService.getDocumentImplList(ids);
        return success(BizDocumentImplConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得文件落实分页")
    @PreAuthorize("@ss.hasPermission('biz:document-impl:query')")
    public CommonResult<PageResult<BizDocumentImplRespVO>> getDocumentImplPage(@Valid BizDocumentImplPageReqVO pageVO) {
        PageResult<BizDocumentImplDO> pageResult = documentImplService.getDocumentImplPage(pageVO);
        return success(BizDocumentImplConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出文件落实 Excel")
    @PreAuthorize("@ss.hasPermission('biz:document-impl:export')")
    @OperateLog(type = EXPORT)
    public void exportDocumentImplExcel(@Valid BizDocumentImplExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<BizDocumentImplDO> list = documentImplService.getDocumentImplList(exportReqVO);
        // 导出 Excel
        List<BizDocumentImplExcelVO> datas = BizDocumentImplConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "文件落实.xls", "数据", BizDocumentImplExcelVO.class, datas);
    }

    @GetMapping("/getAttach")
    @ApiOperation("获取附件")
    public CommonResult<List<OssDO>> getAttach(@Valid String path){
        if(path !=null && !path.equals("")){
            Collection<String> fileIds=Arrays.asList(path.split(","));
            return success(ossService.selectByIds(fileIds));
        }else{
            return success(new ArrayList<>());
        }
    }

    @PostMapping(value = "/downAttachTemplate")
    @ApiOperation("下载文件落实的模板")
    public HttpServletResponse downAttachTemplate(HttpServletResponse response,HttpServletRequest request) {
        try {
            String filename = "作业活动导入模板.xlsx";
            InputStream fis = this.getClass().getClassLoader().getResourceAsStream("template/文件落实导入模板.xls");
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            //response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

    @PostMapping("/import")
    @ApiOperation("导入文件落实")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "Excel 文件", required = true, dataTypeClass = MultipartFile.class)})
    public CommonResult<BizDocumentImplImportRespVO> importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        List<BizDocumentImplExcelVO> list = ExcelUtils.read(file, BizDocumentImplExcelVO.class);
        return success(documentImplService.importExcel(list));
    }
}
